var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
// var logger = require('morgan');
//加载日志模板
var log4js=require('./utils/log4js/log.js');
const logger = log4js.getLogger();
//引入api中的js，然后可以进行访问js里面的路径
var httpDate = require('./api/httpDate');

//生成token和验证token
var vertoken=require('./api/token.js')
var expressJwt=require('express-jwt')


var app = express();

log4js.useLogger(app,logger)


//导入发送求的api
// var api = require('./routes/httpDate.js');
// api(app);
// 使用swagger API 文档
var swaggerInstall = require('./utils/swagger')
swaggerInstall(app)


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



//解析token获取用户信息
app.use(function(req, res, next) {
  var token = req.headers['api_key'];
  console.log(token);
  if(token == undefined){
      return next();
  }else{
    vertoken.getToken(token).then((data)=> {
      req.data = data;
      return next();
  }).catch((error)=>{
      return next();
  })

  }
});

//验证token是否过期并规定那些路由不需要验证
app.use(expressJwt({
  secret:'zgs_first_token',
  algorithms:['HS256']
}).unless({
  path:['/httpDate/login','/httpDate/register','/whyApi']  //不需要验证的接口名称
}))

//token失效返回信息
app.use(function(err,req,res,next){
  console.log(req.data,"asdfasdf");
  if(err.status==401 && !req.data){
      return res.status(401).send('token失效')
       //可以设置返回json 形式  res.json({message:'token失效'})
  }else{
    return next();
  }
})


// app.use('/', indexRouter);
// app.use('/users', usersRouter);
//里面是api，到时候调用的就是里面的 
app.use('/httpDate', httpDate);




// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});



// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
